import java.io.IOException;
import java.io.RandomAccessFile;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Random;

public class KeyGen {

	final static int p = 1031;
	final static int uIndex = (int)(Math.random()*p);
	final static int x = (int)(Math.random()*p);
	final static int vIndex = x;
	final static int wIndex = (uIndex * x);
	final static int g1 = 2;
	final static int g2 = 2;
	
	final int blockLen = 1024;  
	final int maxBlockNum = 1024;
	
	private BigInteger[] sigmaIndexArray = new BigInteger[maxBlockNum];
	private int blockNum =0 ;
	private int fileLen = 0;
	private byte[] msg = new byte[4096];
	private String fileName;
	
	public KeyGen(String fileName_){
		fileName = fileName_;
	}
	
	private int getX(){
		return (int)(Math.random()*p);
	}
	
	
	
	public BigInteger[] getSigmaIndexArray(){
		return sigmaIndexArray;
	}
	
	
	public int getBlockNum(){
		return blockNum;
	}
	
	public int getFileLen(){
		return fileLen;
	}
	
	public int keyGen(){
		RandomAccessFile rFile = null;
		RandomAccessFile wFile = null;
		try{
			rFile = new RandomAccessFile(fileName,"r");
			fileLen=(int)(rFile.length());
			wFile = new RandomAccessFile("audit","rw");
			int bIndex = 0;
			rFile.seek(bIndex);
			byte[] buffer = new byte[blockLen];
			int byteRead = 0;
			int blockIndex = 0;
			while ((byteRead=rFile.read(buffer))!=-1){
				blockIndex++;
				System.out.write(buffer,0,byteRead);
				System.out.print("\n");
				wFile.write(buffer);
				BigInteger m = new BigInteger("0");
				for (int i = 0 ; i < byteRead ; i++){
					m=m.add(BigInteger.valueOf(buffer[i]));
					m=m.shiftLeft(8);
				}
				
				
				m = m.mod(BigInteger.valueOf(p));
				int remain = m.intValue();

				int HashI = HashMethod.getHHash(blockIndex);
				BigInteger uIndexB=new BigInteger(String.valueOf(uIndex));
				BigInteger remainB = new BigInteger(String.valueOf(remain));
				BigInteger sigmaIndex = uIndexB.multiply(remainB);
				//sigmaIndex %= p;
				sigmaIndex=sigmaIndex.add(new BigInteger(String.valueOf(HashI)));
				//sigmaIndex %= p;
				sigmaIndex = sigmaIndex.multiply(new BigInteger(String.valueOf(x)));
				//sigmaIndex %= p;
				//System.out.println(sigmaIndex);
				//wFile.write(sigmaIndex);
				sigmaIndexArray[blockIndex-1]= sigmaIndex;

			}
			blockNum = blockIndex;
			//for (int i = 0; i < blockIndex; i ++){
			//	wFile.writeInt(sigmaIndexArray[i]);
			//}
			System.out.println("blockNum is:"+blockNum);
		}catch(IOException e){
			System.out.println("read file error");
		}
		return 0;
	}
}
